package com.cloud.apigateway.sdk.utils;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;

import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 客户端工具类，用于生成签名和创建HTTP请求
 */
public class Client {
    
    /**
     * 对请求进行签名
     * @param request 请求对象
     * @param algorithm 签名算法
     * @return 签名后的HTTP请求对象
     */
    public static HttpRequestBase sign(Request request, String algorithm) {
        try {
            // 创建URI对象
            URI uri = new URIBuilder(request.getUrl()).build();
            
            // 根据请求方法创建相应的HTTP请求对象
            HttpRequestBase httpRequest = new HttpPost(uri);
            
            // 添加所有请求头
            request.getHeaders().forEach(httpRequest::addHeader);
            
            // 如果是POST请求，设置请求体
            if (httpRequest instanceof HttpPost && request.getBody() != null) {
                ((HttpPost) httpRequest).setEntity(new StringEntity(request.getBody()));
            }
            
            // 生成并添加签名头
            String signature = generateSignature(request, algorithm);
            httpRequest.addHeader("Authorization", "SDK-HMAC-SHA256 Credential=" + request.getKey() + ", Signature=" + signature);
            
            return httpRequest;
            
        } catch (URISyntaxException e) {
            throw new RuntimeException("Failed to create URI: " + e.getMessage(), e);
        } catch (java.io.UnsupportedEncodingException e) {
            throw new RuntimeException("Failed to encode request: " + e.getMessage(), e);
        }
    }
    
    /**
     * 生成签名
     * @param request 请求对象
     * @param algorithm 签名算法
     * @return 签名字符串
     * @throws java.io.UnsupportedEncodingException 当字符编码不支持时抛出
     */
    private static String generateSignature(Request request, String algorithm) throws java.io.UnsupportedEncodingException {
        try {
            // 构建签名字符串
            String stringToSign = request.getMethod() + "\n"
                    + request.getUrl() + "\n"
                    + (request.getBody() != null ? request.getBody() : "");
            
            // 使用HMAC-SHA256算法生成签名
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash = md.digest((stringToSign + request.getSecret()).getBytes());
            
            // 转换为Base64编码
            return Base64.getEncoder().encodeToString(hash);
            
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to generate signature: " + e.getMessage(), e);
        }
    }
}